//
//  LibraryViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/27.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class LibraryViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, CardViewDelegate, SearchViewControllerDelegate {

    var collectionView: UICollectionView!
    
    var printView: UploadFileView!
    
    var uploadBtn: UIBarButtonItem!
    
    var refreshControl: UDRefreshControl!
    var pageControl: UDRefreshControl!
    var fileList: NSDictionary?
    var timeKeys: [String]?
    
    var filePreView : FileOLPreView!
    
    var emptyView: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "我的文库"
        navigationController?.navigationBar.barStyle = .black
        navigationController?.navigationBar.barTintColor = themeColor2
        navigationController?.navigationBar.tintColor = UIColor.white
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(LibraryViewController.goBack))
        
//        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(LibraryViewController.gotoSearch))
        uploadBtn = UIBarButtonItem(title: "上传", style: .plain, target: self, action: #selector(LibraryViewController.gotoUpload))
        navigationItem.rightBarButtonItem = uploadBtn
        
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil)
        
        let collectLayout = UICollectionViewFlowLayout()
        collectLayout.itemSize = CGSize(width: view.bounds.width/2 - 1, height: 80)
        collectLayout.minimumInteritemSpacing = 1
        collectLayout.minimumLineSpacing = 1
        collectLayout.scrollDirection = .vertical
        collectLayout.headerReferenceSize = CGSize(width: view.bounds.height, height: 32)
        
        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: collectLayout)
        collectionView.backgroundColor = UIColor.groupTableViewBackground
        collectionView.alwaysBounceVertical = true
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "item")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        collectionView.delegate = self
        collectionView.dataSource = self
        view.addSubview(collectionView)
        refreshControl = UDRefreshControl(frame: CGRect(x: 0, y: -120, width: view.frame.width, height: 64))
        collectionView.addSubview(refreshControl)
        
        collectionView.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
        
        let searchBtn = UIButton(frame: CGRect(x: 0, y: -44, width: view.bounds.width, height: 44))
        searchBtn.backgroundColor = UIColor.lightGray
        collectionView.addSubview(searchBtn)
        
        let searchBarView = UILabel(frame: CGRect(x: 8, y: 8, width: view.bounds.width-16, height: 28))
        searchBarView.text = "搜索文件"
        searchBarView.font = UIFont.systemFont(ofSize: 14)
        searchBarView.textColor = UIColor.lightGray
        searchBarView.textAlignment = .center
        searchBarView.layer.cornerRadius = 8
        searchBarView.layer.masksToBounds = true
        searchBarView.backgroundColor = UIColor.white
        searchBtn.addSubview(searchBarView)
        searchBtn.addTarget(self, action: #selector(LibraryViewController.gotoSearch), for: .touchUpInside)
        
        pageControl = UDRefreshControl(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 64))
        pageControl.normalTitle = "加载更多"
        
        emptyView = UILabel(frame: CGRect(x: 16, y: 64, width: view.frame.width - 32, height: 64))
        emptyView.font = UIFont.systemFont(ofSize: 14)
        emptyView.text = "暂无数据"
        emptyView.textAlignment = .center
        emptyView.textColor = UIColor.lightGray
        collectionView.addSubview(emptyView)
        
        printView = UploadFileView(frame: view.frame)
        printView.delegate = self
        view.addSubview(printView)
        
        printView.nextBtn.addTarget(self, action: #selector(LibraryViewController.goPlaceOrder), for: .touchUpInside)
        
        filePreView = FileOLPreView(frame: view.frame, vc: self)
        filePreView.delegate = self
        view.addSubview(filePreView)
        filePreView.uploadBtn.addTarget(self, action: #selector(LibraryViewController.gotoPrint(sender:)), for: .touchUpInside)
//        filePreView.deleteBtn.addTarget(self, action: #selector(LibraryViewController.deleteCloudFile(sender:)), for: .touchUpInside)
        filePreView.menuBtn.addTarget(self, action: #selector(LibraryViewController.showMenu(sender:)), for: .touchUpInside)
//        filePreView.alpha = 1
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        refreshList()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y < -192{
            if refreshControl.state == .normal{
                refreshControl.readyToRefresh()
            }
            
        }else{
            if refreshControl.state == .ready{
                refreshControl.endRefresh()
            }
            
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if refreshControl.state == .ready{
            refreshList()
        }
    }
    
    func refreshList(){
        refreshControl.beginRefresh()
        var insert = collectionView.contentInset
        insert.top += 64
        collectionView.contentInset = insert
        
        URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=getMobileList")!) { (data:Data?, re:URLResponse?, err:Error?) in
            DispatchQueue.main.async {
                self.refreshControl.endRefresh()
                var insert = self.collectionView.contentInset
                insert.top -= 64
                UIView.animate(withDuration: 0.3, animations: {
                    self.collectionView.contentInset = insert
                })
            }
            do{
                if err != nil{
                    throw err!
                }
                
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                
                self.fileList = jsonData
                
                let allKeys = jsonData?.allKeys as? [String]
                self.timeKeys = allKeys?.sorted(by: { (a, b) -> Bool in
                    return a > b
                })
                
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                    self.emptyView.alpha = 1
                    if self.fileList != nil{
                        if self.fileList!.count > 0{
                            self.emptyView.alpha = 0
                        }
                    }
                }
                
            }catch let ex{
                print(ex)
            }
        }.resume()
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return fileList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        let allobjs = fileList?.allValues
//        if allobjs != nil{
//            let dateAry = allobjs![section] as? [Any]
//            if dateAry != nil{
//                return dateAry!.count
//            }
//        }
        
        if fileList != nil && timeKeys != nil {
            let dateAry = fileList?.object(forKey: timeKeys![section]) as? [Any]
            if dateAry != nil{
                return dateAry!.count
            }
        }
        
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var header = UICollectionReusableView()
        if kind == UICollectionElementKindSectionHeader{
            header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
            let bgView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 28))
            bgView.backgroundColor = UIColor.groupTableViewBackground
            header.addSubview(bgView)
            let timeLabel = UILabel(frame: CGRect(x: 16, y: 4, width: view.bounds.width - 32, height: 20))
            bgView.addSubview(timeLabel)
            timeLabel.text = "分组"
            if timeKeys != nil{
                timeLabel.text = timeKeys![indexPath.section]
            }
            
            
        }
        return header
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath)
        cell.backgroundColor = UIColor.white
        
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height))
        bgView.backgroundColor = UIColor.white
        cell.addSubview(bgView)
        
        let icon = UIImageView(frame: CGRect(x: 8, y: 8, width: 44, height: 63))
        icon.image = #imageLiteral(resourceName: "doc_icon")
        icon.contentMode = .scaleAspectFit
        bgView.addSubview(icon)
        
        let nameLabel = UILabel(frame: CGRect(x: 60, y: 8, width: view.bounds.width/2 - 1 - 54 - 16, height: 36))
        nameLabel.font = UIFont.systemFont(ofSize: 14)
        nameLabel.numberOfLines = 2
        nameLabel.lineBreakMode = .byTruncatingMiddle
        bgView.addSubview(nameLabel)
        
        let pageLabel = UILabel(frame: CGRect(x: 60, y: 48, width: nameLabel.frame.width - 32, height: 20))
        pageLabel.font = UIFont.systemFont(ofSize: 14)
        pageLabel.textColor = UIColor.lightGray
        bgView.addSubview(pageLabel)
        
//        let printBtn = FCPrintButton(frame: CGRect(x: view.bounds.width/2 - 1 - 20 - 8, y: pageLabel.frame.origin.y + 4, width: 20, height: 20))
//        printBtn.indexPath = indexPath
//        printBtn.setImage(#imageLiteral(resourceName: "printer_green"), for: .normal)
//        printBtn.imageView?.contentMode = .scaleAspectFit
//        bgView.addSubview(printBtn)
//        printBtn.addTarget(self, action: #selector(LibraryViewController.gotoPrint(sender:)), for: .touchUpInside)
//        
//        let deleteBtn = FCPrintButton(frame: CGRect(x: printBtn.frame.origin.x, y: 4, width: 20, height: 20))
//        deleteBtn.indexPath = indexPath
//        deleteBtn.setTitle("×", for: .normal)
//        deleteBtn.setTitleColor(UIColor.lightGray, for: .normal)
//        deleteBtn.titleLabel?.font = UIFont.systemFont(ofSize: 24)
//        bgView.addSubview(deleteBtn)
//        deleteBtn.addTarget(self, action: #selector(LibraryViewController.deleteCloudFile(sender:)), for: .touchUpInside)
        
//        let fileItem = fileList?.object(at: indexPath.row) as? NSDictionary
        
        if fileList != nil && timeKeys != nil{
            let dateAry = fileList?.object(forKey: timeKeys![indexPath.section]) as? [Any]//fileList!.allValues[indexPath.section] as? [Any]
            if dateAry != nil{
                let fileItem = dateAry![indexPath.row] as? NSDictionary
                
                nameLabel.text = fileItem?.object(forKey: "fileName") as? String
                
                var pnum = fileItem?.object(forKey: "num") as? String
                if pnum == nil{
                    let pnumInt = fileItem?.object(forKey: "num") as? Int
                    if pnumInt != nil{
                        pnum = "\(pnumInt!)"
                    }
                }
                if pnum != nil{
                    if pnum != "0" {
                        pageLabel.text = "\(pnum!)页"
                    }
                }
            }
        }
        
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("\(indexPath.section)-\(indexPath.row)")
        
        if fileList != nil && timeKeys != nil{
            let dateAry = fileList?.object(forKey: timeKeys![indexPath.section]) as? [Any]//fileList!.allValues[indexPath.section] as? [Any]
            if dateAry != nil{
                let fileItem = dateAry![indexPath.row] as? NSDictionary
                let fileName = fileItem?.object(forKey: "fileName") as? String
                let fileID = fileItem?.object(forKey: "itemId") as? String
                print(fileID ?? "")
                filePreView.openFile(fileName: fileName, fileID: fileID)
                navigationItem.rightBarButtonItem = nil
                filePreView.indexPath = indexPath
                
            }
        }
    }
    
    func goBack(){
        dismiss(animated: true, completion: nil)
    }
    
    func gotoSearch(){
        print("gotoSearch")
        let searchVC = SearchViewController()
        searchVC.delegate = self
        present(searchVC, animated: false, completion: nil)
    }
    
    func gotoUpload(){
        present(TutorialViewController(), animated: true, completion: nil)
    }
    
    func cardViewClose(_ cardView: UIView) {
        navigationItem.rightBarButtonItem = uploadBtn
    }
    
    func gotoPrint(sender: FCPrintButton){
        
        var fileID = filePreView.fileID
        var fileName = filePreView.fileName
        var pnum = filePreView.filePage
        
        if sender.indexPath != nil{
            
            print("open print view \(sender.indexPath!.section)-\(sender.indexPath!.row)")
            
            if fileList != nil && timeKeys != nil{
                let dateAry = fileList?.object(forKey: timeKeys![sender.indexPath!.section]) as? [Any]//fileList!.allValues[indexPath.section] as? [Any]
                if dateAry != nil{
                    let fileItem = dateAry![sender.indexPath!.row] as? NSDictionary
                    fileName = fileItem?.object(forKey: "fileName") as? String
                    fileID = fileItem?.object(forKey: "itemId") as? String
                    print(fileID ?? "")
                    
                    pnum = fileItem?.object(forKey: "num") as? String
                    if pnum == nil{
                        let pnumInt = fileItem?.object(forKey: "num") as? Int
                        if pnumInt != nil{
                            pnum = "\(pnumInt!)"
                        }
                    }
                    
                }
            }
            
        }
        
        if fileID != nil {
            filePreView.hideView()
            printView.showView(FCPrintFile(fileName: fileName, fileSize: nil, filePage: pnum, fileID: fileID))
            navigationItem.rightBarButtonItem = nil
        }
        
        
        
        
        
    }
    
    func goPlaceOrder(){
        printView.countInput.resignFirstResponder()
        if printView.file != nil{
            printView.hideView()
            
            let fileInfo = ["file": printView.file!, "paperOption": printView.paperOption, "goods_number":printView.quantity] as NSDictionary
            
            let shopVC = ShopSelectViewController(files: [fileInfo])
            shopVC.step0VC = self
            navigationController?.pushViewController(shopVC, animated: true)
        }
        
    }
    
    func showMenu(sender: FCPrintButton){
        let menu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
//        menu.addAction(UIAlertAction(title: "分享", style: .default, handler: { (action) in
//
//        }))
        menu.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { (action) in
            self.deleteCloudFile(sender: sender)
        }))
        menu.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(menu, animated: true, completion: nil)
        
        
    }
    
    func deleteCloudFile(sender: FCPrintButton){
        
        var fileID = filePreView.fileID
        
        if sender.indexPath != nil{
            print("delete file \(sender.indexPath!.section)-\(sender.indexPath!.row)")
            if self.fileList != nil && self.timeKeys != nil{
                let dateAry = self.fileList?.object(forKey: self.timeKeys![sender.indexPath!.section]) as? [Any]//fileList!.allValues[indexPath.section] as? [Any]
                if dateAry != nil{
                    let fileItem = dateAry![sender.indexPath!.row] as? NSDictionary
                    fileID = fileItem?.object(forKey: "itemId") as? String
                    print(fileID ?? "")
                }
            }
        }
        
        
        
        let alert = UIAlertController(title: "删除文件?", message: "删除后不可恢复", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { (action) in
            
            
            let url = "\(apiBaseDomainName)?m=admin&c=goods&a=deleteFile&f=\(fileID ?? "")"
            print(url)
            
            URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data, _, err) in
                do{
                    if err != nil{
                        throw err!
                    }
                    
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let reCode = jsonObj?.object(forKey: "code") as? Int
                    
                    if reCode == 200{
                        DispatchQueue.main.async {
                            self.refreshList()
                            self.filePreView.hideView()
                        }
                    }else{
                        let alert = UIAlertController(title: "删除失败", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
                    
                }catch let ex{
                    let alert = UIAlertController(title: "删除失败", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    print(ex)
                }
            }).resume()
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        self.present(alert, animated: true, completion: nil)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func searchViewController(_ vc: SearchViewController, didSelectSearchFile filename: String?, fileID: String?, filePage: String?) {
        printView.hideView()
        filePreView.indexPath = nil
        filePreView.fileName = filename
        filePreView.fileID = fileID
        filePreView.filePage = filePage
        
        filePreView.openFile(fileName: filename, fileID: fileID)
        navigationItem.rightBarButtonItem = nil
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
class FCPrintButton: UIButton{
    var indexPath: IndexPath?
}
